package com.devunion.bogdan.model.project;


import org.springframework.beans.factory.InitializingBean;
import org.apache.commons.io.FileUtils;

import java.io.File;

/**
 * @author Timoshenko Alexander 20.06.2009 : 13:06:02
 */
public class RelativePathConverter implements InitializingBean {
    private static String sep = File.separator;
    private String root;

    public void afterPropertiesSet() throws Exception {
        
        File file = new File(root);
        if (!file.exists()) {
            FileUtils.forceMkdir(file);
        }

        root = file.getAbsolutePath();
        if ((root != null) && !root.endsWith(sep)) {
            root += sep;
        }
    }

    public void setRoot(String root) {
        this.root = root;
    }

    public String projectPath(String porject) {
        return new File(root, porject != null ? porject : "default").getAbsolutePath();
    }

    public String getRelativePath(String path) {
        if (path.startsWith(root)) {
            return new String(path.substring(root.length()));
        }

        return null;
    }

    /**
     * Gets a root property value.
     *
     * @return the root
     */
    public String getRoot() {
        return root;
    }

    public String getAbsolutePath(String projectName, String path) {
        return new File(root + projectName, path).getAbsolutePath();
    }

    public String getRelativePath(File file) {
        return getRelativePath(file.getAbsolutePath());
    }
}
